/**
 * 
 */
package org.wolf.core.schema;

import java.util.Locale;
import java.util.UUID;

import org.apache.lucene.document.Fieldable;

/**
 * @author 何小锋
 * 
 */
public class UUIDField extends FieldType {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final String NEW = "NEW";
	private static final char DASH = '-';

	@Override
	public void setTokenized(boolean tokenized) {
	}

	@Override
	public String toInternal(Object value) {
		if (value == null)
			return UUID.randomUUID().toString().toLowerCase(Locale.US);
		if (value != null && value instanceof UUID)
			return ((UUID) value).toString().toLowerCase(Locale.US);
		String val = value.toString();
		if (val.isEmpty() || NEW.equals(val)) {
			return UUID.randomUUID().toString().toLowerCase(Locale.US);
		} else {
			if (val.length() != 36 || val.charAt(8) != DASH
					|| val.charAt(13) != DASH || val.charAt(18) != DASH
					|| val.charAt(23) != DASH) {
				throw new IllegalArgumentException("Invalid UUID String: '"
						+ val + "'");
			}

			return val.toLowerCase(Locale.US);
		}
	}

	@Override
	public Object toExternal(Fieldable f) {
		return UUID.fromString(f.toString());
	}

}
